package com.hgx.alibab.consumer.order02.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.hgx.alibab.consumer.order02.entity.Payment;
import com.hgx.alibab.consumer.order02.service.IPaymentFeignService;
import com.hgx.springcloud.common.entities.response.CommonResultResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
public class CircleBreakerController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/consumer/fallback/{id}")
//    @SentinelResource(value = "fallback")
//    @SentinelResource(value = "fallback",fallback = "handleFallBack")
//    @SentinelResource(value = "fallback",blockHandler = "blockHandler")
    @SentinelResource(value = "fallback", fallback = "handleFallBack", blockHandler = "blockHandler", exceptionsToIgnore = {IllegalArgumentException.class})
    public CommonResultResponse fallback(@PathVariable("id") Integer id) {
        CommonResultResponse forObject = restTemplate.getForObject("http://nacos-provider-payment" +
                "/payment/" + id, CommonResultResponse.class);

        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException 异常-----");
        } else if (forObject.getData() == null) {
            throw new NullPointerException("NULL Exception,空空。。。");
        }
        return forObject;
    }

    public CommonResultResponse handleFallBack(@PathVariable("id") Integer id, Throwable e) {
        return new CommonResultResponse<>("444", "handleFallBack异常处理方法" + e.getMessage(), new Payment(id, "00000"));
    }

    public CommonResultResponse blockHandler(@PathVariable("id") Integer id, BlockException e) {
        return new CommonResultResponse<>("445", "blockHandler异常处理方法" + e.getMessage(), new Payment(id, "00000"));
    }


    @Resource
    private IPaymentFeignService paymentFeignService;


    @GetMapping("/consumer/fallbackFeign/{id}")
//    @SentinelResource(value = "fallbackFeign", blockHandler = "blockHandler")
    public CommonResultResponse<Payment> fallbackFeign(@PathVariable("id") Integer id) {
        return paymentFeignService.getPayment(id);
    }


}
